import { hasToken } from "../../utils/storage";
import { Route, Redirect, RouteProps, useLocation } from "react-router-dom";

interface AuthRouteType extends RouteProps {
  component?: any;
}

export default function AuthRoute({ children, component: Component, ...rest }: AuthRouteType) {
  const location = useLocation();
  console.log(hasToken());

  return (
    <Route
      {...rest}
      render={(props) => {
        if (hasToken()) {
          if (children) {
            if (typeof children === "function") {
              return children(props);
            } else {
              return children;
            }
          } else {
            return <Component />;
          }
        } else {
          return (
            <Redirect
              to={{
                pathname: "/login",
                state: {
                  from: location.pathname,
                },
              }}
            ></Redirect>
          );
        }
      }}
    ></Route>
  );
}
